package com.example.itcompanyinterview.tools;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.ListIterator;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.os.Environment;
import android.util.Pair;

public class CommonUrlRequest {
	
	public static String getControllerAndAction(String controller, String action) {
		return getControllerAndAction(controller, action, null);
	}
	
	public static String getControllerAndAction(String controller, String action, List<Pair<String, String>> param) {
		String targetUrl = makeActionUrl(controller, action, param);
		return httpGetResultFromUrl(targetUrl);
	}
	
	private static String makeActionUrl(String controller, String action, List<Pair<String, String>> param) {
		String requestUrl = ApplicationDefination.urlPrefix + ApplicationDefination.controllerPrefix + "=" 
				+ controller + ApplicationDefination.PARAM_DELIMTER
				+ ApplicationDefination.actionPrefix + "=" + action;
		if(param != null) {
			ListIterator<Pair<String, String>> iter = param.listIterator();
			while (iter.hasNext()) {
				Pair<String, String> pair = iter.next();
				String paramName = pair.first;
				String paramValue = pair.second;
				requestUrl = requestUrl + ApplicationDefination.PARAM_DELIMTER
						+ paramName + "=" + paramValue;

			}
		}
		return requestUrl;
	}
	
	public static String postControllerAndAction(String controller, String action, List<NameValuePair> params) {
		String targetUrl = makeActionUrl(controller, action, null);
		return httpPostDataToUrl(targetUrl, params);
	}
	
	public static String httpPostDataToUrl(String url, List<NameValuePair> params) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost httpRequset = new HttpPost(url);
        try{
        	String HttpResult = "";
        	httpRequset.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
	        HttpResponse httpResponse = httpClient.execute(httpRequset);
	        if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	        	HttpResult = EntityUtils.toString(httpResponse.getEntity());
	        	return HttpResult;
	        } else {
	        	return null;
	        }
	       
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
		return null;
	}
	
	public static String httpGetResultFromUrl(String url) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpRequset = new HttpGet(url);
        try{
        	String HttpResult = "";
	        HttpResponse httpResponse = httpClient.execute(httpRequset);
	        if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	        	HttpResult = EntityUtils.toString(httpResponse.getEntity());
	        	return HttpResult;
	        } else {
	        	return null;
	        }
	       
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
		return null;
	}
	
	public static void setParam(List<Pair<String, String>> paramList, String paramName, String paramValue) {
		Pair<String, String> paramPair = new Pair<String, String>(paramName, paramValue);
		paramList.add(paramPair);
	}
	
	public static int SaveUrlFiletoLocal(String fileUrl, String path) {
		try {
			URL url = new URL(fileUrl);
			URLConnection urlConn = url.openConnection();
			
			String contentType = urlConn.getContentType();
			if (contentType.startsWith("text/")) {
				return -1;
			}
			
			byte[] data = readBytesFromUrlConnection(urlConn);

			String filename = getFileNameFromUrl(fileUrl);
			String Outputfilename = CommonFileTools.getLocalPath(path) + "/" + filename;
			writeBytesToFile(data, Outputfilename);
		}catch(Exception e) {
			e.printStackTrace();
			return -1;
		}
		return 0;
	}
	
	private static byte[] readBytesFromUrlConnection(URLConnection urlConn) throws IOException {
		int contentLength = urlConn.getContentLength();
		if(contentLength == -1) { 
			return null;
		}
		
		InputStream raw = urlConn.getInputStream();
		InputStream in = new BufferedInputStream(raw);
		byte[] data = new byte[contentLength];
		int bytesRead = 0;
		int offset = 0;
		while (offset < contentLength) {
			bytesRead = in.read(data, offset, data.length - offset);
			if (bytesRead == -1)
				break;
			offset += bytesRead;
		}
		in.close();

		if (offset != contentLength) {
			return null;
		}
		
		return data;
	}
	
	private static void writeBytesToFile(byte[] data, String filename) throws IOException {
		File file = new File(filename);
		if(file.getParentFile().exists() == false) {
			file.getParentFile().mkdirs();
		}
		FileOutputStream fout = new FileOutputStream(file);
		fout.write(data);
		fout.flush();
		fout.close();
	}
	
	public static String getFileNameFromUrl(String url) {
		return url.substring(url.lastIndexOf('/') + 1);
	}

}
